//
//  FinderDetailViewController.m
//  ForYourBeauty
//
//  Created by Kelly xu on 2019/6/2.
//  Copyright © 2019 changrenTech. All rights reserved.
//

#import "FinderDetailViewController.h"
#import "FinderTitleCell.h"
#import "ReportImgCell.h"
#import "ReportTextCell.h"
#import <WebKit/WebKit.h>
#import "FinderViewModel.h"
@interface FinderDetailViewController ()<UITableViewDelegate,UITableViewDataSource,WKUIDelegate,WKNavigationDelegate>{
    
}
@property(nonatomic,weak)IBOutlet UIImageView *webBg;
@property(nonatomic,weak)IBOutlet UIButton *favBtn;
@property(nonatomic,weak)IBOutlet UIButton *likeBtn;
@property(nonatomic,strong)FinderViewModel *finderViewModel;
@property(nonatomic,strong)FinderDetailModel *finderDetailModel;
@property(nonatomic,strong)WKWebView *mainWeb;
@end

@implementation FinderDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self deleteWebCache];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"详情";
    self.webBg.userInteractionEnabled = YES;
    self.webBg.layer.cornerRadius = 10;
    self.webBg.clipsToBounds = YES;
//    [self setNavRightBtn:@"分享" color:nil];
    [self configWebView];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self.finderViewModel fetchFinderDetail:self.finderId cmp:^(FinderDetailModel * _Nonnull detailModel) {
        self.finderDetailModel = detailModel;
        if(self.finderDetailModel.like){
            self.favBtn.selected = YES;
        }
        if(self.finderDetailModel.top){
            self.likeBtn.selected = YES;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
//            NSString *headerString = @"<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></header>";
//            [self.mainWeb loadHTMLString:[headerString stringByAppendingString:self.finderDetailModel.articleContet] baseURL:nil];
            [self.mainWeb loadHTMLString:self.finderDetailModel.articleContet baseURL:nil];
        });
    }];
}
-(void)configWebView{
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    // 设置偏好设置
    config.preferences = [[WKPreferences alloc] init];
    // 默认为0
    config.preferences.minimumFontSize = 10;
    // 默认认为YES
    config.preferences.javaScriptEnabled = YES;
    // 在iOS上默认为NO，表示不能自动通过窗口打开
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    // web内容处理池，由于没有属性可以设置，也没有方法可以调用，不用手动创建
    config.processPool = [[WKProcessPool alloc] init];
    // 通过JS与webview内容交互
    config.userContentController = [[WKUserContentController alloc] init];
    
    self.mainWeb = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.webBg.width,self.webBg.height) configuration:config];
    self.mainWeb.autoresizingMask = UIViewAutoresizingFlexibleHeight| UIViewAutoresizingFlexibleWidth;
    self.mainWeb.UIDelegate = self;
    self.mainWeb.navigationDelegate = self;
    self.mainWeb.allowsBackForwardNavigationGestures = NO;
    self.mainWeb.backgroundColor = [UIColor whiteColor];
    self.mainWeb.scrollView.bounces = NO;
    self.mainWeb.scrollView.delegate = self;
    [self.webBg addSubview:self.mainWeb];
}
#pragma mark - fav&like
-(IBAction)favBtnPressed:(id)sender{
    UIButton *button = (UIButton*)sender;
    if (!button.selected) {
        [self.finderViewModel addToLikeList:self.finderId cmp:^{
            button.selected = !button.selected;
        }];
    }else{
        [self.finderViewModel delFromLikeList:self.finderId cmp:^{
            button.selected = !button.selected;
        }];
    }
}
-(IBAction)likeBtnPressed:(id)sender{
    UIButton *button = (UIButton*)sender;
    if (!button.selected) {
        [self.finderViewModel addToTopList:self.finderId cmp:^{
            button.selected = !button.selected;
        }];
    }else{
        [self.finderViewModel delFromTopList:self.finderId cmp:^{
            button.selected = !button.selected;
        }];
    }
}
#pragma mark - instance
-(FinderViewModel*)finderViewModel{
    if (!_finderViewModel) {
        _finderViewModel = [[FinderViewModel alloc]init];
    }
    return _finderViewModel;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [SVProgressHUD show];
    NSLog(@"%s",__func__);
}
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    NSLog(@"%s",__func__);
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"%s",__func__);
    [SVProgressHUD dismiss];
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"%s %@",__func__,error);
    [SVProgressHUD dismiss];
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"%s %@",__func__,error);
    [SVProgressHUD dismiss];
}
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView
{
    NSLog(@"%s",__func__);
    [self.mainWeb reload];
}

// 在JS端调用alert函数时，会触发此代理方法。
// JS端调用alert时所传的数据可以通过message拿到
// 在原生得到结果后，需要回调JS，是通过completionHandler回调
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    NSLog(@"%s", __FUNCTION__);
    dispatch_async(dispatch_get_main_queue(), ^{
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            completionHandler();
        }]];
        
        [self presentViewController:alert animated:YES completion:NULL];
        
    });
    
    
    NSLog(@"%@", message);
}
// JS端调用confirm函数时，会触发此方法
// 通过message可以拿到JS端所传的数据
// 在iOS端显示原生alert得到YES/NO后
// 通过completionHandler回调给JS端
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
    NSLog(@"%s", __FUNCTION__);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            completionHandler(YES);
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            completionHandler(NO);
        }]];
        [self presentViewController:alert animated:YES completion:NULL];
    });
    
    NSLog(@"%@", message);
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler {
    
    completionHandler(@"Client Not handler");
    
}
/**
 *  清除缓存
 */
- (void)deleteWebCache {
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        NSSet *websiteDataTypes
        = [NSSet setWithArray:@[
                                WKWebsiteDataTypeDiskCache,
                                WKWebsiteDataTypeOfflineWebApplicationCache,
                                WKWebsiteDataTypeMemoryCache,
                                WKWebsiteDataTypeLocalStorage,
                                WKWebsiteDataTypeCookies,
                                WKWebsiteDataTypeSessionStorage,
                                WKWebsiteDataTypeIndexedDBDatabases,
                                WKWebsiteDataTypeWebSQLDatabases
                                ]];
        //// All kinds of data
        //        NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
        //// Date from
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        //// Execute
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            // Done
        }];
        
    } else {
        
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
        
    }
}
@end
